#coding=utf-8
import librosa
import os
import json
import numpy as np


# 

# # for t in onset_amp:
# # 	print(t)

def save_data(data):
 	f=open("level.json","w")
 	# f=open("level.json","a+")
 	f.write(json.dumps(data)+",")
 	f.close()


def analysis(nameKey,path,configJosn):
	y, sr = librosa.load(path)
	tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)

	#获取音乐时间
	musicTimer=librosa.get_duration(filename=path)
	#将时间转化为帧数
	musicFrame=librosa.time_to_frames(musicTimer)
	#获取每个节拍平均相隔几帧   每首歌的节拍是大概固定的
	beatsDis=musicFrame/len(beat_frames)



	# #能量起跳点  帧数
	# onsets_frames = librosa.onset.onset_detect(y)
	# #能量起跳点帧数转时间
	# onsets_frames_to_timer= librosa.frames_to_time(onsets_frames, sr=sr)


	# 峰值点 帧数
	onset_env = librosa.onset.onset_strength(y=y, sr=sr,hop_length=512,aggregate=np.median)
	peaks = librosa.util.peak_pick(onset_env, 3, 3,3, 5, 0.5, 12)
	peaks_to_timer= librosa.frames_to_time(peaks, sr=sr)
	# print(peaks_to_timer)

	# 计算每一帧所有频率点幅度的均值。
	mel = np.abs(librosa.feature.melspectrogram(y, fmax=11025))
	amp_db = librosa.power_to_db(mel)
	
	diff = np.maximum(amp_db[:,1:] - amp_db[:,:-1], 0.0)
	onset_amp = np.mean(diff, axis=0)
	onset_amp -= onset_amp.min()
	onset_amp /= onset_amp.max()


	#去所有幅度的平均值
	allAMP=0
	for amp in onset_amp:
		allAMP=allAMP+amp
	averageAMP=allAMP/len(onset_amp)

	#存储每个起跳点的信息
	onsetFrameTimer=[]
	#遍历峰值 获取帧数
	for i in range(len(peaks)):
		# frame=peaks[i]-1
		# amp=onset_amp[frame]
		# if amp>averageAMP:
		onsetFrameTimer.append(peaks_to_timer[i])
			# print(peaks_to_timer[i])
	
	dataStr="[0,"
	for item in onsetFrameTimer:
		dataStr=dataStr+str(item)+","
	dataStr=dataStr[:len(dataStr)-1]
	dataStr=dataStr+"]"

	ampStr="[0,"
	for item in onset_amp:
		ampStr=ampStr+str(item)+","
	ampStr=ampStr[:len(ampStr)-1]
	ampStr=ampStr+"]"
	
	json={}
	json["timer"]=musicTimer
	# json["amp"]=ampStr
	json["rhythm"]=dataStr
	configJosn[nameKey]=json

# audioName="music/0_0.mp3"
# analysis(audioName)

def getFileList(configJosn):
	audioList = os.listdir('music')
	for tmp in audioList:
		audioPath = os.path.join('music', tmp)
		if audioPath.endswith('.mp3'):
			name=tmp[:tmp.find('.mp3')]
			print("print "+audioPath+" audio datas----")
			analysis(name,audioPath,configJosn)
if __name__=="__main__":
	configJosn={}
	getFileList(configJosn)
	save_data(configJosn)








	# # for frame in onsets_frames:
	# # 	#获取当前帧数的 幅度




	# #提取所有起跳点的幅度值
	# onset_frame_out_amp=[]
	# for item in onsets_frames:
	# 	onset_frame_out_amp.append(onset_amp[item-1])

	
	

	# #提取起跳点幅度大于平均幅度的帧数
	# okFrame=[]
	# for i in range(0,len(onsets_frames)):
	# 	if onset_frame_out_amp[i]<
	# 	# print(i)

	

	# 
	# 
	# print(aa/len(beat_frames))
	# all=0
	# for item in beat_frames:
	# 	all=all+item
	# print(all,all/(len(onset_amp)))
		# print(len(beat_frames)/tempo)
	# print(beat_frames)







	# frameAll=len(onset_amp)
	# timer=librosa.get_duration(filename=audioName)

	# frameRate=timer/frameAll;
	# dataStr="["
	# for i in range(0,frameAll):
	# 	if onset_amp[i]>minS:
	# 		frameTimer=i*frameRate
	# 		dataStr=dataStr+str(frameTimer)+","
	# dataStr=dataStr[:len(dataStr)-1]
	# dataStr=dataStr+"]"
	# json={}
	# json["frameAll"]=frameAll
	# json["frameRate"]=frameRate
	# json["timer"]=timer
	# json["dataStr"]=dataStr
	# # save_data(json)



# beat_frames=librosa.frames_to_time(beat_frames)
# print(beat_frames)
# pointStr='['
# for t in beat_frames:
#  	pointStr=pointStr+str(t)+","
 	

# f=open("point.json","a+")
# f.write(pointStr)
# f.close()



# path=os.getcwd()
# print(path)
# audioList = os.listdir('music')
# raw_audioList = {}
# beat_database = {}
# for tmp in audioList:
#     audioName = os.path.join('music', tmp)
#     # audioName=path+"/music/aa.MP3"
#     if audioName.endswith('.wav'):
#         print(tmp)
#         y, sr = librosa.load(audioName)
#         tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
#         aa=librosa.frames_to_time(beat_frames, sr=sr)
#         print(aa)
#         # 
#         # beat_frames = librosa.feature.delta(beat_frames)

#         # beat_database[audioName] = beat_frames

#         # print(beat_database)
